import React, { Component } from 'react'
import { Card, Table, Button, Modal, Form, Input, Select, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { antiShake } from "../../utils/antiShake"
import http from "../../api"
import getTime from "../../config/huoQuDate"
import "./index.css"

const { Option } = Select
const { confirm } = Modal

export default class UserManagement extends Component {
  columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'name',
    },
    {
      title: '电话',
      dataIndex: 'telephone',
      key: 'telephone',
    },
    {
      title: '注册时间',
      dataIndex: 'register_tiem',
      key: 'register_tiem',
    },
    {
      title: '所属角色',
      dataIndex: 'roleId',
      key: 'roleId',
      render: ({name}) => {
        return name
      }
    },
    {
      title: '操作',
      width: '200px',
      align: 'center',
      key: 'caozuo',
      render: () => {
        return (
          <>
            <Button type="link" onClick={this.updateUser}>修改</Button>&nbsp;&nbsp;
            <Button type="link" onClick={this.deleteUser}>删除</Button>
          </>
        )
      }
    }
  ]
  state = { users: [], roles: [], user: {}, visible: false, update: false }
  componentDidMount() {
    this.getRoles()
    this.getUser()
  }
  // 异步获取角色数据
  getRoles = async() => {
    const { data } = await http.get('/rest/role/whole')
    this.setState({ roles: data })
  }
  // 异步获取用户数据
  getUser = async() => {
    const { data } = await http.get('/rest/login/whole')
    this.setState({ users: data })
  }
  // 创建用户按钮回调
  showModal = () => {
    this.setState({ visible: true })
  }
  // 弹出框，确认按钮
  hideModal = async() => {
    const register_tiem = getTime()
    const { username, password, telephone, roleId, update } = this.state
    // 表单验证
    if(!this.formValidation()) return ;
    const userObj = { username, password, telephone, roleId, register_tiem }
    let item = {}
    // 判断是否是更新信息
    if(update) {
      const { _id } = this.state.user
      item = await http.post('/rest/login/update', { _id, ...userObj })
      this.setState({ username: '', password: '', telephone: '', roleId: '' })
    } else {
      item = await http.post('/rest/login', userObj)
    }
    // 重新获取用户数据
    this.getUser()
    message.success(item.data.message)
    this.setState({ visible: false, update: false })
  }
  // 表单统一验证
  formValidation = () => {
    const { username, password, telephone, roleId } = this.state
    const patt = /[ ]/g
    if(patt.test(username) || !username) {
      message.error('用户名不能为空，且不含空格')
      return false
    }
    if(patt.test(password) || !password) {
      message.error('密码不能为空，且不含空格')
      return false
    }
    if(patt.test(telephone) || !telephone) { 
      message.error('手机号不能为空，且不含空格')
      return false
    } 
    if(patt.test(roleId) || !roleId) {
      message.error('角色不能为空')
      return false
    }
    return true
  }
  // 更新用户
  updateUser = () => {
    setTimeout(() => {
      // 获取要修改的用户信息
      const { username, password, telephone, roleId } = this.state.user
      this.setState({ username, password, telephone, roleId: roleId._id })
    })
    this.setState({ update: true, visible: true })
  }
  // 删除用户
  deleteUser = () => {
    confirm({
      title: '确定删除该用户吗?',
      okText: '确定',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async()=> {
        const { _id } = this.state.user
        const { data } = await http.delete('/rest/login/delete', {
          params: { _id }
        })
        // 重新获取用户数据
        this.getUser()
        message.success(data.message)
      }
    })
  }
  render() {
    const { users, roles, user, update, visible } = this.state
    const title = <Button type="primary" onClick={this.showModal}>创建用户</Button>
    return (
      <>
        <Card title={title}>
          <Table
            bordered={true}
            dataSource={users}
            columns={this.columns}
            pagination={{
              pageSize: 5,
              position: ['bottomCenter'],
            }}
            onRow={record => {
              return {
                onClick: () => {
                  this.setState({ user: record })
                },
              };
            }}
          />
        </Card>
        {
          visible && <Modal
          title="创建角色"
          visible={visible}
          onOk={this.hideModal}
          onCancel={() => { this.setState({ username: '', password: '', telephone: '', roleId: '', update: false, visible: false }) }}
          okText="确认"
          cancelText="取消"
        >
          <Form id="user-form">
            <Form.Item label="用户名" name="name" initialValue={ update ? user.username : '' }>
              <Input
                placeholder="请输入用户名"
                onChange={(e) => {
                  antiShake(500, () => {this.setState({ username: e.target.value })}, e)
                }}
              />
            </Form.Item>
            <Form.Item label="密码" name="password" initialValue={ update ? user.password : '' }>
              <Input 
                placeholder="请输入密码" 
                onChange={(e) => {
                  antiShake(500, () => {this.setState({ password: e.target.value })}, e)
                }}
              />
            </Form.Item>
            <Form.Item label="手机号" name="telephone" initialValue={ update ? user.telephone : '' }>
              <Input 
                placeholder="请输入手机号" 
                onChange={(e) => {
                  antiShake(500, () => {this.setState({ telephone: e.target.value })}, e)
                }}
              />
            </Form.Item>
            <Form.Item label="角色" name="roleId" initialValue={ update ? user.roleId._id : '' }>
              <Select placeholder="请选择角色" onChange={value => this.setState({roleId: value})}>
                {
                  roles.map(item => {
                    return <Option value={item._id} key={item._id}>{item.name}</Option>
                  })
                }
              </Select>
            </Form.Item>
          </Form>
        </Modal>
        }
      </>
    )
  }
}
